/*
 * @Description: useCallback使用
 * @Author: ZhangHan
 * @Date: 2025-04-16 16:04:06
 * @LastEditTime: 2025-04-16 16:18:47
 * @LastEditors: ZhangHan
 */
import { useState, useCallback, memo } from "react";
import { InputNumber, Space, Select, Button, Card, Divider } from "antd";

// 定义子组件的props类型
interface CounterButtonProps {
  onClick: () => void;
  label: string;
}

// 使用 memo 优化的子组件，添加类型定义
const CounterButton = memo(({ onClick, label }: CounterButtonProps) => {
  console.log(`子组件 ${label} 渲染`); // 用于观察渲染情况
  return <Button onClick={onClick}>{label}</Button>;
});

// 定义普通按钮的props类型
interface NormalButtonProps {
  onClick: () => void;
  label: string;
}

// 未优化的子组件，添加类型定义
const NormalButton = ({ onClick, label }: NormalButtonProps) => {
  console.log(`普通子组件 ${label} 渲染`); // 用于观察渲染情况
  return <Button onClick={onClick}>{label}</Button>;
};

function MineCallback() {
  const [count, setCount] = useState(0);
  const [price, setPrice] = useState(100);
  const [currency, setCurrency] = useState("CNY");
  
  // 使用 useCallback 优化的回调函数
  const handleIncrement = useCallback(() => {
    setCount((c) => c + 1);
  }, []);
  
  // 未使用 useCallback 的回调函数
  const handleDecrement = () => {
    setCount((c) => c - 1);
  };
  
  // 依赖 price 和 currency 的回调函数
  const calculateTotal = useCallback(() => {
    const rate = {
      CNY: 1,
      USD: 0.15,
      EUR: 0.13
    };
    alert(`总价: ${(price * rate[currency]).toFixed(2)} ${currency}`);
  }, [price, currency]);

  return (
    <Card title="useCallback 使用示例" style={{ width: 500, margin: "20px auto" }}>
      <Space direction="vertical" style={{ width: "100%" }}>
        <Divider orientation="left">计数器示例</Divider>
        
        <div>当前计数: {count}</div>
        
        <Space>
          <CounterButton 
            onClick={handleIncrement} 
            label="增加 (memo优化)" 
          />
          <CounterButton 
            onClick={handleDecrement} 
            label="减少 (memo优化)" 
          />
          <NormalButton 
            onClick={handleIncrement} 
            label="增加 (普通)" 
          />
        </Space>

        <Divider orientation="left">价格计算示例</Divider>
        
        <Space>
          <InputNumber 
            value={price} 
            onChange={(value) => setPrice(value || 0)} 
            min={0} 
            addonBefore="价格" 
          />
          
          <Select
            value={currency}
            onChange={(value) => setCurrency(value)}
            options={[
              { value: "CNY", label: "人民币" },
              { value: "USD", label: "美元" },
              { value: "EUR", label: "欧元" }
            ]}
            style={{ width: 120 }}
          />
          
          <Button onClick={calculateTotal}>计算总价</Button>
        </Space>
      </Space>
    </Card>
  );
}

export default MineCallback;